package team27.service;

import java.util.ArrayList;
//import java.util.List;
import javax.ws.rs.Consumes;
import javax.ws.rs.CookieParam;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
//import javax.ws.rs.core.Cookie;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.NewCookie;
import javax.ws.rs.core.Request;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;
import javax.ws.rs.core.UriInfo;
import javax.xml.bind.JAXBElement;

import team27.messaging.Chatroom;
import team27.messaging.Message;
import team27.messaging.MessageDao;

//maps this resource to the URL orders
@Path("/")
public class MessageService 
{
	@Context
	UriInfo uriInfo;
	@Context
	Request request;
	
	// Return the list of orders for applications with json or xml formats
	@GET
	@Produces(MediaType.APPLICATION_JSON)
	public ArrayList<Message> getOrders( @CookieParam("count") String count ) 
	{
		ArrayList<Message> messages = new ArrayList<Message>();
		messages.addAll(MessageDao.instance.getModel().values());
		return messages;
	}
	
	@PUT
	@Consumes({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
	public Response putMessage(@CookieParam("count") String count ,JAXBElement<Message> msg)
	{
		
		Chatroom.messages.add( msg.getValue() );
		return putAndGetResponse(msg.getValue() , count) ;
	}
	
	
 
	@POST
	@Consumes(MediaType.APPLICATION_JSON)
	public Response sendBack( @CookieParam(value = "count") String count, Message msg )
	{
		Chatroom.messages.add( msg );
	    int nc = 0;
	    if (count != null )
	    	nc = Integer.parseInt(count);
		String newCount = Integer.toString( nc + msg.message.length());
		System.out.println( count );
		return Response.status(Status.OK ).cookie( new NewCookie("count", newCount )).build();
	}
	
	
	 private Response putAndGetResponse(Message msg , String count) {
		    Response res;
		    int nc = 0;
		    if (count != null )
		    	nc = Integer.parseInt(count);
		    
		    String newCount = Integer.toString( nc  + msg.message.length());
		    res = Response.ok().cookie(new NewCookie ("count", newCount )).build();
		    
		    System.out.println(newCount);
		    
		    MessageDao.instance.getModel().put(msg.chatroom, msg);
		    return res;
		    
	 }
	
	
	
}


